package client

import (
	"context"
	"fmt"
	"io/ioutil"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/json"
	"k8s.io/apimachinery/pkg/util/yaml"

	"k8s.io/klog/v2"
)

func GetService(ns string) {
	clientSet, err := CreateClientSet()
	if err != nil {
		klog.Error(err)
	}
	opts := metav1.ListOptions{
		Watch: false,
	}

	srv, err := clientSet.CoreV1().Services(ns).List(context.TODO(), opts)
	for _, v := range srv.Items {
		klog.Info(v.Name,v.Spec)
	}
}

func CreateService(ns string, serviceFile string) {
	clientSet, err := CreateClientSet()
	if err != nil {
		klog.Error(err)
	}
	serviceClient := clientSet.CoreV1().Services(ns)
	var (
		data       []byte
		service= &corev1.Service{}
	)
	if data, err = ioutil.ReadFile(serviceFile); err != nil {
		fmt.Printf("readfile: %v",err)
	}
	if data, err = yaml.ToJSON(data); err != nil {
		fmt.Printf("yaml to json: %v",err)
		return
	}
	if err = json.Unmarshal(data, service); err != nil {
		return
	}
	serviceName := service.ObjectMeta.Name
	fmt.Println(serviceName)
	if _, err = serviceClient.Get(context.TODO(), serviceName, metav1.GetOptions{}); err != nil {
		if !errors.IsNotFound(err) {
			fmt.Println(err)
			return
		}
		if _, err = serviceClient.Create(context.TODO(), service, metav1.CreateOptions{}); err != nil {
			fmt.Println(err)
			return
		}
	} else {
		if _, err = serviceClient.Update(context.TODO(), service, metav1.UpdateOptions{}); err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("service creat succse!")
	return
}

